<template>
  <div>
    <PageTools>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="点位搜索">
          <el-input v-model="formInline.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="区域搜索">
          <el-select
            v-model="formInline.regionId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in NodeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="Search"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </PageTools>
    <el-card class="main">
      <el-button
        style="margin-bottom: 10px"
        type="primary"
        size="small"
        icon="el-icon-circle-plus-outline"
        @click="addForm"
      >新建</el-button>
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="list"
        style="width: 100%"
        :header-cell-style="{
          fontWeight: 'normal',
          background: '#f3f6fb',
        }"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column label="点位名称" prop="name" />
        <el-table-column label="所在区域" prop="region.remark" />
        <el-table-column label="商圈类型" prop="businessType.name" />
        <el-table-column label="合作商" prop="ownerName" />
        <el-table-column label="详细地址" prop="addr" :formatter="addrType" />
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              size="small"
              @click="detailsFn(row)"
            >查看详情</el-button>
            <el-button
              type="text"
              size="small"
              @click="editFn(row)"
            >修改</el-button>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row
        v-if="totalPage !== 1"
        type="flex"
        justify="space-between"
        align="middle"
      >
        <el-col :span="19">
          <p class="paginationHeader">
            {{ `共${totalCount}条记录 第${page.pageIndex}/${totalPage}页` }}
          </p>
        </el-col>
        <el-col :span="5">
          <el-pagination
            background
            :current-page="pageNode.pageIndex"
            :page-size="pageNode.pageSize"
            :total="totalCount"
            layout="prev, next"
            prev-text="上一页"
            next-text="下一页"
            @current-change="changePage"
          />
        </el-col>
      </el-row>
    </el-card>
    <!-- 新增点位 -->
    <el-dialog
      class="dialog"
      :title="title"
      :visible="dialogNode.dialogShow"
      width="45%"
      @close="closeDialog"
      @open="openDialog"
    >
      <el-form
        ref="NodeRef"
        label-width="120px"
        :model="dialogNode.NodeForm"
        :rules="dialogNode.NodeFormRules"
      >
        <el-form-item label="点位名称:" prop="name">
          <el-input
            v-model="dialogNode.NodeForm.name"
            type="text"
            placeholder="请输入"
            maxlength="15"
            show-word-limit
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="所在区域:" prop="regionId">
          <el-select
            v-model="dialogNode.NodeForm.regionId"
            placeholder="请选择"
            clearable
            style="width: 80%"
          >
            <el-option
              v-for="item in NodeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在商圈:" prop="businessId">
          <el-select
            v-model="dialogNode.NodeForm.businessId"
            placeholder="请选择"
            clearable
            style="width: 80%"
          >
            <el-option
              v-for="item in businessList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商:" prop="ownerName">
          <el-select
            v-model="dialogNode.NodeForm.ownerName"
            placeholder="请选择"
            clearable
            style="width: 80%"
            @change="getOwner($event)"
          >
            <el-option
              v-for="item in ownerNameList"
              :key="item.id"
              :label="item.name"
              :value="`${item.id}|${item.name}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址:" prop="addr">
          <el-cascader
            v-model="selectedOptions"
            size="large"
            :options="options"
            style="width: 80%"
            @change="addressChange"
          />
        </el-form-item>
        <el-form-item prop="detailAddr">
          <el-input
            v-model="detailAddr"
            placeholder="请输入详细地址"
            style="width: 80%"
            type="textarea"
            :rows="3"
            maxlength="60"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancel" @click="closeDialog">取 消</el-button>
        <el-button
          type="primary"
          class="sure"
          @click="dialogNodeFn"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 查看点位详情 -->
    <DetailNode
      :node-id="NodeId"
      :details-visible="detailsVisible"
      @closeDialog="closeDialogFn"
    />
  </div>
</template>

<script>
import DetailNode from './component/detail-node.vue'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import {
  Regionsearch,
  Nodesearch,
  GetbusinessType,
  Partnersearch,
  addNode,
  updataNodeList
} from '@/api/node'
export default {
  components: {
    DetailNode
  },
  data() {
    return {
      formInline: { name: '', regionId: '' },
      loading: false,
      list: [],
      page: {
        pageIndex: 1,
        pageSize: 100000
      },
      pageNode: { pageIndex: 1, pageSize: 10 },
      totalCount: 0,
      totalPage: 0,
      NodeList: [],
      businessList: [],
      ownerNameList: [],
      options: regionData, // 地区下拉列表
      // selectedOptions: ['440000', '440300', '440304'] // 省市区id
      selectedOptions: [], // 省市区id
      addr: '',
      detailAddr: '', // 详细地址
      dialogNode: {
        dialogShow: false,
        NodeForm: {
          name: '',
          regionId: '',
          businessId: '', // 所属商圈
          ownerName: '', // 归属合作商
          ownerId: '', // 归属合作商Id
          addr: '', // 详细地址
          areaCode: '', // 地址市的编号
          createUserId: 1 // 创建人id
        },
        NodeFormRules: {
          name: [{ required: true, message: '请输入', trigger: 'change' }],
          regionId: [{ required: true, message: '请输入', trigger: 'change' }],
          businessId: [
            { required: true, message: '请输入', trigger: 'change' }
          ],
          ownerName: [{ required: true, message: '请输入', trigger: 'change' }],
          addr: [{ required: true, message: '请输入', trigger: 'change' }]
        }
      },
      detailsVisible: false, // 点位详情显示和隐藏
      NodeId: ''
    }
  },
  computed: {
    title() {
      return this.dialogNode.NodeForm.id ? '修改点位' : '新增点位'
    }
  },
  created() {
    this.Regionsearch()
    this.Nodesearch()
  },
  methods: {
    // 区域搜索下拉数据
    async Regionsearch() {
      const { data } = await Regionsearch(this.page)
      this.NodeList = data.currentPageRecords
    },
    // 表格数据
    async Nodesearch(name) {
      this.loading = true
      const { data } = await Nodesearch({ ...this.pageNode, ...name })
      this.list = data.currentPageRecords
      this.loading = false
      this.totalCount = Number(data.totalCount)
      this.totalPage = Number(data.totalPage)
    },
    // 1.查询
    Search() {
      this.Nodesearch(this.formInline)
    },
    // 2.新增
    addForm() {
      this.dialogNode.dialogShow = true
    },
    // 3.分页
    changePage(val) {
      this.pageNode.pageIndex = val
      this.Nodesearch()
    },
    // 4.查看详情
    detailsFn(row) {
      this.NodeId = row.id
      this.detailsVisible = true
    },
    // 4.1.查看详情关闭
    closeDialogFn() {
      this.detailsVisible = false
    },
    // 4.1.修改
    editFn(row) {
      this.dialogNode.dialogShow = true
      this.dialogNode.NodeForm = row
      const data = this.dialogNode.NodeForm.addr.split('-')
      this.detailAddr = data[data.length - 1]
      if (data.length >= 2) {
        this.selectedOptions = [
          TextToCode[data[0]].code,
          TextToCode[data[0]][data[1]].code,
          TextToCode[data[0]][data[1]][data[2]].code
        ]
      }
    },
    // 5.地址是字符串取到最后一位
    addrType(row, column, callValue, index) {
      const arr = callValue.split('-')
      const str = arr[arr.length - 1]
      return str
    },
    // 6.新增点位--弹出层
    // 6.1.关闭
    closeDialog() {
      // this.$refs.NodeRef.resetFields()
      this.dialogNode.NodeForm = {
        name: '',
        regionId: '',
        businessId: '', // 所属商圈
        ownerName: '', // 归属合作商
        ownerId: '', // 归属合作商Id
        addr: '', // 详细地址
        areaCode: '' // 地址市的编号
        // createUserId: '' // 创建人id
      }
      this.selectedOptions = []
      this.detailAddr = ''
      this.dialogNode.dialogShow = false
    },
    // 6.2.确定
    async dialogNodeFn() {
      this.$refs.NodeRef.validate(async(isOk) => {
        if (!isOk) return
        this.dialogNode.NodeForm.addr =
          this.dialogNode.NodeForm.addr + '-' + this.detailAddr
        if (this.dialogNode.NodeForm.id) {
          await updataNodeList(this.dialogNode.NodeForm)
        } else {
          await addNode(this.dialogNode.NodeForm)
        }
        this.Nodesearch()
        this.dialogNode.dialogShow = false
      })
    },
    // 6.3.新增点位打开请求表单下拉数据
    async openDialog() {
      const { data } = await GetbusinessType()
      this.businessList = data
      const res = await Partnersearch(this.page)
      this.ownerNameList = res.data.currentPageRecords
    },
    // 6.4.归属合作商需要得到label和value传递给表单
    getOwner(val) {
      console.log(val)
      const [id, name] = val.split('|')
      this.dialogNode.NodeForm.ownerName = name
      this.dialogNode.NodeForm.ownerId = Number(id)
    },
    // 6.5 详细地址转换
    addressChange(val) {
      this.selectedOptions = val
      // console.log(this.selectedOptions)//['110000', '110100', '110105']
      // console.log(CodeToText[110100])--市辖区
      this.dialogNode.NodeForm.addr = ''
      this.dialogNode.NodeForm.areaCode = this.selectedOptions[1]
      this.selectedOptions.forEach((item, index) => {
        if (index === 0) {
          this.dialogNode.NodeForm.addr += CodeToText[item]
        } else {
          this.dialogNode.NodeForm.addr += '-' + CodeToText[item]
        }
      })
    }
  }
}
</script>
<style lang="scss">
</style>
